package com.jokins.admin.vue.gitlog.action;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jokins.admin.vue.gitlog.actioncontext.GetGiteeLogsListDoc;
import com.jokins.admin.vue.gitlog.mapper.GitWebhookMapper;
import com.jokins.admin.vue.gitlog.param.GitPushLogsParam;
import com.jokins.admin.vue.gitlog.vo.GitPushLogsVo;
import com.jokins.common.actions.action.ActionContext;
import com.jokins.common.actions.action.BaseAction;
import com.jokins.common.actions.exception.BusinessException;
import com.jokins.common.entry.vue.gitlog.GitPushLogs;
import com.jokins.common.util.SqlTypeConverter;
import com.jokins.common.util.date.DateFormatter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component
public class GetGiteeLogsListDocAction extends BaseAction<GetGiteeLogsListDoc> {

    @Autowired
    private GitWebhookMapper gitWebhookMapper;

    @Override
    protected void process(GetGiteeLogsListDoc actionContext) throws BusinessException {
        GitPushLogsParam param = actionContext.getParam();
        log.info("进入GetGiteeLogsListDocAction。。。。。");
        String applyName = param.getApplyName();
        log.info("Executing GetGiteeLogsList SQL query...");
        QueryWrapper<GitPushLogs> queryWrapper = new QueryWrapper<>();
        Optional.ofNullable(applyName)
                .filter(name -> !name.isEmpty())
                .ifPresent(name -> queryWrapper.eq("repository_name", name).orderByDesc("created_time"));
        List<GitPushLogs> gitPushLogsList = gitWebhookMapper.selectList(queryWrapper);
        List<GitPushLogsVo> gitPushLogsVoList = gitPushLogsList.stream()
                .map(apply -> {
                    GitPushLogsVo vo = new GitPushLogsVo();
                    SqlTypeConverter.convertEntity(apply, vo, DateFormatter.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
                    ObjectMapper objectMapper = new ObjectMapper();
                    try {
                        Object json = objectMapper.readValue(apply.getComment(), Object.class);
                        vo.setComment(json);
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                    return vo;
                })
                .collect(Collectors.toList());
        log.info("Fetched gitPushLogsList: {}", gitPushLogsVoList);
        log.info("gitPushLogsList:{}", JSON.toJSONString(gitPushLogsVoList));
        actionContext.setResult(ActionContext.RESULT_DOC_KEY, gitPushLogsVoList);
    }
}
